<template>
  <div class="app-container">
    <!-- 高级搜索 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="联系方式" prop="customerPhone">
        <el-input
          v-model="queryParams.customerPhone"
          placeholder="请输入客户联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号码" prop="licensePlate">
        <el-input
          v-model="queryParams.licensePlate"
          placeholder="请输入车牌号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="岗位状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.appoint_serv_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
     <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:appointment:add']"
          >新增</el-button
        >
      </el-col>
       <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:appointment:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:appointment:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:appointment:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="appointmentList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="微信用户ID" align="center" prop="wxUserId">
        <template slot-scope="rows">
          {{ rows.row.wxUserId | wxNameFormat }}
        </template>
      </el-table-column>
      <el-table-column
        label="客户联系方式"
        align="center"
        prop="customerPhone"
      />
      <el-table-column
        label="预约时间"
        align="center"
        prop="appointmentTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.appointmentTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="实际到店时间"
        align="center"
        prop="actualArrivalTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.actualArrivalTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车牌号码" align="center" prop="licensePlate" />
      <el-table-column label="汽车类型" align="center" prop="carSeries" />
      <el-table-column label="服务类型" align="center" prop="serviceType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.appoint_serv_type"
            :value="scope.row.serviceType"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="info" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.appoint_serv_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="130px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            :disabled="scope.row.status !== 0"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:appointment:edit']"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-shop"
            v-hasPermi="['business:appointment:edit']"
            @click="handleArrived(scope.row)"
            :disabled="scope.row.status !== 0"
            >到店</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            :disabled="scope.row.status != 1 && scope.row.status != 4 && scope.row.status != 5"
            @click="generateStatment(scope.row)"
            >结算单</el-button
          >
          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
          >
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                icon="el-icon-error"
                command="cancelOP"
                :disabled="scope.row.status !== 0"
                >取消</el-dropdown-item
              >
              <el-dropdown-item
                icon="el-icon-delete"
                command="deleteOP"
                :disabled="scope.row.status !== 0"
                >删除</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改养修信息预约对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :rules="rules">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="联系方式" prop="customerPhone">
          <el-input
            v-model="form.customerPhone"
            placeholder="请输入客户联系方式"
          />
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker
            clearable
            v-model="form.appointmentTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择预约时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="车牌号码" prop="licensePlate">
          <el-input v-model="form.licensePlate" placeholder="请输入车牌号码" />
        </el-form-item>
        <el-form-item label="汽车类型" prop="carSeries">
          <el-input v-model="form.carSeries" placeholder="请输入汽车类型" />
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceType">
          <el-select
            v-model="form.serviceType"
            placeholder="请输入服务类型"
            clearable
          >
            <el-option
              v-for="dict in dict.type.appoint_serv_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息" prop="info">
          <el-input v-model="form.info" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAppointment,
  getAppointment,
  delAppointment,
  addAppointment,
  updateAppointment,
  arrivedAppointment,
  cancelAppointment,
  generateStatement,
  getStatement
} from "@/api/business/appointment";
import r from "highlight.js/lib/languages/r";

export default {
  name: "Appointment",
  dicts: ["appoint_serv_status", "appoint_serv_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 养修信息预约表格数据
      appointmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerPhone: null,
        licensePlate: null,
        serviceType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customerPhone: [
          { required: true, message: "请输入客户联系方式", trigger: "blur" },
          { min: 11, max: 11, message: "请输入11位客户联系方式", trigger: "blur" },
          { pattern: /^[1][3-9][0-9]{9}$/, message: "请输入正确的客户联系方式", trigger: "blur" },
        ],
        appointmentTime: [
          { required: true, message: "请选择预约时间", trigger: "change" },
          // { type: "date", message: "请选择正确的时间", trigger: "change" },
        ],
        licensePlate: [
          { required: true, message: "请输入车牌号码", trigger: "blur" },
          { min: 7, max: 8, message: "请输入7-8位车牌号码", trigger: "blur" },
          { pattern: /^[\u4e00-\u9fa5][A-Z][A-Z0-9]{5,6}$/, message: "请输入正确的车牌号码", trigger: "blur" },
        ],
        carSeries: [{ required: true, message: "请输入汽车类型", trigger: "blur" }],
        serviceType: [
          { required: true, message: "请选择服务类型", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询养修信息预约列表 */
    getList() {
      this.loading = true;
      listAppointment(this.queryParams).then((response) => {
        this.appointmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮操作
    cancelOP(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认取消养修信息预约')
        .then(function () {
          return cancelAppointment(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("取消成功");
        })
        .catch(() => {});
    }, 
    // 删除按钮操作
    deleteOP(row) {
      this.handleDelete(row);
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "cancelOP":
          this.cancelOP(row);
          break;
        case "deleteOP":
          this.deleteOP(row);
          break;
        default:
          break;
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        wxUserId: null,
        customerPhone: null,
        appointmentTime: null,
        actualArrivalTime: null,
        licensePlate: null,
        carSeries: null,
        serviceType: null,
        createTime: null,
        info: null,
        status: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加养修信息预约";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAppointment(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改养修信息预约";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateAppointment(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAppointment(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除养修信息')
        .then(function () {
          return delAppointment(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 到店按钮操作 */
    handleArrived(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('用户是否到店？')
        .then(function () {
          return arrivedAppointment(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("到店成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/appointment/export",
        {
          ...this.queryParams,
        },
        `appointment_${new Date().getTime()}.xlsx`
      );
    },
    // 生成结算单
    generateStatment(row) {
      let id = row.id || this.ids;
      const status = row.status || this.status;
      // 当前状态为 1，提示用户生成结算单
      if (status == 1) {
        this.$modal
          .confirm('结算单不存在，是否生成？')
          .then(() => {
            return generateStatement(id);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("结算单生成成功");
            // 然后跳转页面
            this.toStatementItem(id);
          })
          .catch(() => {});
      } else if(status == 4 || status == 5) {
        // 当前状态为 4 或 5，根据id跳转结算单页面
        this.toStatementItem(id);
      } else {
        this.$modal.msgWarning("当前状态不允许生成或跳转结算单");
      }
    },
    // 根据id查结算单id
    toStatementItem(id) {
      getStatement(id).then((response) => { 
        // 判断结算单是否存在
        if (response.data == null) {
          this.$modal
          .confirm('结算单不存在，是否生成？')
          .then(() => {
            return generateStatement(id);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("结算单生成成功");
            // 然后跳转页面
            this.toStatementItem(id);
          })
          .catch(() => {});
        } else {
          // 跳转页面
          this.$router.push("/business/statement/item/" + response.data.id)
        }
      })
    },
  },
  filters: {
    // 微信名过滤器
    wxNameFormat(name) {
      return name ? name : "客服录入";
    },
  },
};
</script>
